define(['jquery', 'bootstrap', 'backend', 'table', 'form','knowbase','toastr'], function ($, undefined, Backend, Table, Form,Knowbase,ToastrV2) {
    // https://ask.fastadmin.net/article/12383.html
    ToastrV2.options = Fast.config.toastr;
    ToastrV2.options.positionClass = 'toast-top-center';
    var Controller = {
        index: function () {
            // ��ʼ������������
            Table.api.init({
                extend: {
                    index_url: 'knowbase/project_page/index' + location.search,
                    add_url: 'knowbase/project_page/add?knowbase_project_id='+Fast.api.query('knowbase_project_id'),
                    edit_url: 'knowbase/project_page/edit',
                    del_url: 'knowbase/project_page/del',
                    multi_url: 'knowbase/project_page/multi',
                    import_url: 'knowbase/project_page/import',
                    table: 'knowbase_project_page',
                }
            });

            var table = $("#table");

            var buttons = [ {
                name: 'dragsort',
                icon: 'fa fa-arrows',
                title: __('Drag to sort'),
                extend: 'data-toggle="tooltip"',
                classname: 'btn btn-xs btn-primary btn-dragsort',
                hidden: function (row) {
                    if (Config.project.archive_switch==1){
                        return true;
                    }
                    return false;
                }
            },{
                name: 'create',
                icon: 'fa fa-plus',
                title: __('tips_btn_create'),
                extend: 'data-toggle="tooltip" data-container="body" data-area=["100%","100%"]',
                classname: 'btn btn-xs btn-info  btn-dialog',
                url: function (row){
                    return 'knowbase/project_page/add?pid='+row.id+'&knowbase_project_id='+Fast.api.query('knowbase_project_id');
                },
                hidden:function (row){
                    
                    if (Config.project.archive_switch==1){
                        return true;
                    }
                    
                    if (row.type=='file') {
                        return true;
                    }
                    return false;
                }
            },{
                name: 'link',
                icon: 'fa fa-link',
                title: __('tips_btn_visit'),
                extend: 'target="_blank"',
                classname: 'btn btn-xs btn-default',
                url: function (row){
                    if (row.type=='url') {
                        return row.content;
                    }
                    if (row.project && row.project.identify) {
                        if (row.identify) {
                            return Config.url_knowbase_rewrite_page.replace('{0}',row.project.identify).replace('{1}',row.identify);
                        } else {
                            return Config.url_knowbase_rewrite_page.replace('{0}',row.project.identify).replace('{1}',row.id);
                        }
                    }  else {
                        return Config.url_knowbase_page.replace('{0}',row.id);
                    }
                },
                hidden: function (row) {
                    if (row.status_switch==0){
                        return true;
                    }
                    return false;
                }
            },{
                name: 'edit',
                icon: 'fa fa-pencil',
                title: __('Edit'),
                extend: 'data-toggle="tooltip" data-container="body" data-area=["100%","100%"]',
                classname: 'btn btn-xs btn-success btn-editone',
                hidden:function (row){
                    if (Config.project.archive_switch==1){
                        return true;
                    }
                   
                    return false;
                }
            }, {
                name: 'del',
                icon: 'fa fa-trash',
                title: __('Del'),
                extend: 'data-toggle="tooltip" data-container="body"',
                classname: 'btn btn-xs btn-danger btn-delone',
                hidden: function (row) {
                    if (Config.project.archive_switch==1){
                        return true;
                    }
                    return false;
                }
            },{
                  name: 'clone',
                  icon: 'fa fa-copy',
                  title: __('btn_clone'),
                  classname: 'btn btn-xs btn-warning btn-ajax btn-cloneone',
                  url: 'knowbase/project_page/cloneone',
                  success: function (data, ret) {
                    if (ret.code && ret.code == 1) {
                      table.bootstrapTable('refresh');
                    }
                  },
                  error: function (data, ret) {
                    Layer.alert(ret.msg);
                    return false;
                  },
                  hidden: function (row) {
                      
                    if (Config.project.archive_switch==1){
                        return true;
                    }
                      
                    if (!Config.clone) {
                          return true;
                    }

                    if (row.type == 'file') {
                      return false;
                    }
                    return true;
                  }
            }];

            // ��ʼ�����
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                escape: false,
                pagination: false,
                search: false,
                commonSearch: false,
                sortName: 'weigh',
                columns: [
                    [
                        // {checkbox: true},
                        {field: 'id', title: __('Id')},
                        //{field: 'knowbase_project_id', title: __('Knowbase_project_id')},
                        //{field: 'admin_id', title: __('Admin_id')},
                        // {field: 'type', title: __('Type'), searchList: {"dir":__('Type dir'),"file":__('Type file')}, formatter: Table.api.formatter.normal},
                        //{field: 'pid', title: __('Pid')},
                        {field: 'status_switch', title: __('Status_switch'), searchList: {"1":__('Yes'),"0":__('No')}, table: table, formatter: Table.api.formatter.toggle},
                        {field: 'title', title: __('Title'),align: 'left', operate: 'LIKE',formatter: Controller.api.formatter.title},
                      //  {field: 'identify', title: __('Identify')},
                        //{field: 'attachfiles', title: __('Attachfiles'), operate: false, formatter: Table.api.formatter.files},
                       // {field: 'access_type', title: __('Access_type'), operate: false,searchList: {"0":__('Access_type 0'),"1":__('Access_type 1'),"2":__('Access_type 2'),"3":__('Access_type 3'),"4":__('Access_type 4')}, formatter: Table.api.formatter.normal},
                        //{field: 'password', title: __('Password'), operate: 'LIKE'},
                        //{field: 'user_group_id', title: __('User_group_id')},
                        //{field: 'views', title: __('Views')},
                        //{field: 'py', title: __('Py'), operate: 'LIKE'},
                        //{field: 'pinyin', title: __('Pinyin'), operate: 'LIKE'},
                        {field: 'createtime', title: __('Createtime'),  addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'updatetime', title: __('Updatetime'),  addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        //{field: 'weigh', title: __('Weigh'), operate: false},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate,buttons:buttons}
                    ]
                ],
                rowAttributes: function (row, index) {
                    // ����ȫ��չ���� ����ˢ���ֱ�����������
                    if ($('.btn-toggle-all i').hasClass('fa-minus')) {
                        return {};
                    }
                    return row.pid == 0 ? {} : {style: "display:none"};
                }
            });

            // Ϊ�����¼�
            Table.api.bindevent(table);

            //���������Ⱦǰ
            table.on('pre-body.bs.table', function (e, data) {
                var options = table.bootstrapTable("getOptions");
                options.escape = true;
            });

            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                //��ʾ�����ӽڵ�
                $(">tbody>tr[data-index] > td", this).on('click', "a.btn-node-sub", function () {
                    // ����첽���¼��� ȫ��չ���� �����쳣
                    //var status = $(this).data("shown") ? true : false;
                    var status = $(this).find('i').hasClass('fa-caret-down')?true:false;
                    $("a[data-pid='" + $(this).data("id") + "']").each(function () {
                        $(this).closest("tr").toggle(!status);
                    });
                    if (status) {
                        $("a[data-pid='" + $(this).data("id") + "']").trigger("collapse");
                    }
                    $(this).data("shown", !status);
                    $("i", this).toggleClass("fa-caret-down").toggleClass("fa-caret-right");
                    return false;
                });
            });

            //�����ӽڵ�
            $(document).on("collapse", ".btn-node-sub", function () {
                if ($("i", this).length > 0) {
                    $("a[data-pid='" + $(this).data("id") + "']").trigger("collapse");
                }
                $("i", this).removeClass("fa-caret-down").addClass("fa-caret-right");
                $(this).data("shown", false);
                $(this).closest("tr").toggle(false);
            });

            //չ������һ��
            $(document.body).on("click", ".btn-toggle", function (e) {
                $("a[data-id][data-pid][data-pid!=0].disabled").closest("tr").hide();
                var that = this;
                var show = $("i", that).hasClass("fa-chevron-down");
                $("i", that).toggleClass("fa-chevron-down", !show).toggleClass("fa-chevron-up", show);
                $("a[data-id][data-pid][data-pid!=0]").not('.disabled').closest("tr").toggle(show);
                $(".btn-node-sub[data-pid=0]").data("shown", show);
            });

            //չ������ȫ��
            $(document.body).on("click", ".btn-toggle-all", function (e) {
                var that = this;
                var show = $("i", that).hasClass("fa-plus");
                $("i", that).toggleClass("fa-plus", !show).toggleClass("fa-minus", show);
                $(".btn-node-sub:not([data-pid=0])").closest("tr").toggle(show);
                $(".btn-node-sub").data("shown", show);
                $(".btn-node-sub > i").toggleClass("fa-caret-down", show).toggleClass("fa-caret-right", !show);
            });


        },
        recyclebin: function () {
            // ��ʼ������������
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // ��ʼ�����
            table.bootstrapTable({
                url: 'knowbase/project_page/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'), operate: false},
                        // {field: 'title', title: __('Title'), align: 'left'},
                        {field: 'type', title: __('Type'), searchList: {"dir":__('Type dir'),"file":__('Type file')}, formatter: Table.api.formatter.normal},
                        {field: 'paths', align: 'left', title: __('Paths'), operate: false, formatter: Table.api.formatter.normal},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '140px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'knowbase/project_page/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    confirm: __('sure_delete_pages'),
                                    url: 'knowbase/project_page/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // Ϊ�����¼�
            Table.api.bindevent(table);

        },
        add: function () {
            Controller.api.bindevent();
            this.initListen();
        },
        edit: function () {
            Controller.api.bindevent();
            this.initListen();
            $('#history').click(function (e) {
                e.preventDefault();
                var form = $("form[role=form]");
                var ids = $(this).attr('data-id');
                var pos = window.location.pathname.indexOf('.php');
                var admin = window.location.pathname.substr(0,pos+4);
                Layer.open({
                    type: 2,
                    content: admin+'/knowbase/project_page_history/page_history?knowbase_project_page_id=' + ids,
                    zIndex: 99,
                    area: ['80%','80%'],
                    title: __('btn_look_history'),
                    resize: false,
                    end: function () {
                        if (parent.window.refresh) {
                           window.location.reload();
                           parent.window.refresh = 0;
                        }
                    }
                });
            });
            $('#save').click(function (e){
                var eles = $(Config.knowbase.classname || '.vditor_editor');
                if (eles.length > 0) {
                    for (var i = 0; i < eles.length; i++) {
                        var ele = $(eles[i]);
                        var id = ele.attr('id');
                        if (id && window.vditorlist && window.vditorlist[id]){
                            $('#'+id.replace('-vditor','')).val(window.vditorlist[id].getValue());
                        }
                    }
                }
                var submitResult = Form.api.submit($("form[role=form]"), function (data, ret) {
                    ToastrV2.success(__('Operation completed'));
                    return false;
                }, function (data, ret) {
                    ToastrV2.error(ret.msg);
                    return false;
                });
            });
            document.addEventListener('keydown', function(e) {
                // ����Ƿ����� Ctrl + S
                if (e.ctrlKey && e.key === 's') {
                    // ��ֹĬ�ϵı�����Ϊ
                    e.preventDefault();
                    $('#save').click();
                }
            });

            // ����Ƿ��вݸ�������
            window.hasOldContent = false;
            var key = 'document_'+Knowbase.getId();
            if (Knowbase.getStorage(key)){
                window.hasOldContent = true;
                $('.layer-footer .alert-danger').removeClass('hide');
            }
            $('.layer-footer').on('click','.recover',function (e){
                var content = Knowbase.getStorage(key);
                window.vditorlist['c-content-vditor'].setValue(content);
                $('.layer-footer').find('.remove').trigger('click');
            });
            $('.layer-footer').on('click','.remove',function (e){
                window.hasOldContent = false;
                window.hasOldContent = false;
                $('.layer-footer .alert-warning').addClass('hide');
                $('.layer-footer .alert-danger').addClass('hide');
                Knowbase.removeStorage(key);
            });
            setInterval(function (){
                if (!window.hasOldContent &&  window.changeContent) {
                    $('.layer-footer .alert-warning').removeClass('hide');
                    $('.layer-footer .alert-danger').addClass('hide');
                    $('.layer-footer .alert-warning .text .time').text(Knowbase.getCurrentTimeFormatted());
                    window.changeContent = false;
                    // ��¼��ǰ�汾
                    var content = window.vditorlist['c-content-vditor'].getValue();
                    Knowbase.setStorage(key,content);
                }
            },5000);
            window.openPageLink = function (){
                var page_url = '';
                if (Config.project && Config.project.identify) {
                    if (Config.page.identify) {
                        page_url =  Config.url_knowbase_rewrite_page.replace('{0}',Config.page.project.identify).replace('{1}',Config.page.identify);
                    } else {
                        page_url =  Config.url_knowbase_rewrite_page.replace('{0}',Config.page.project.identify).replace('{1}',Config.page.id);
                    }
                }  else {
                    page_url =  Config.url_knowbase_page.replace('{0}',Config.page.id);
                }
                window.open(page_url);
            };
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"),function () {
                    var eles = $(Config.knowbase.classname || '.vditor_editor');
                    if (eles.length > 0) {
                        for (var i = 0; i < eles.length; i++) {
                            var ele = $(eles[i]);
                            var id = ele.attr('id');
                            if (id && window.vditorlist && window.vditorlist[id]){
                                // ��ֹ�������ֻ���
                                window.vditorlist[id].clearCache();
                            }
                        }
                    }
                }, function () {}, function (success, error) {
                    var eles = $(Config.knowbase.classname || '.vditor_editor');
                    if (eles.length > 0) {
                        for (var i = 0; i < eles.length; i++) {
                            var ele = $(eles[i]);
                            var id = ele.attr('id');
                            if (id && window.vditorlist && window.vditorlist[id]){
                                $('#'+id.replace('-vditor','')).val(window.vditorlist[id].getValue());
                            }
                        }
                    }
                    return true;
                });
            },
            formatter: {
                title: function (value, row, index) {
                    value = value.toString().replace(/(&|&amp;)nbsp;/g, '&nbsp;');
                    var caret = '';
                    if ($('.btn-toggle-all i').hasClass('fa-minus')) {
                        caret = row.type=='dir' ? '<i class="fa fa-caret-down"></i>' : '';
                    } else {
                        caret = row.type=='dir' ? '<i class="fa fa-caret-right"></i>' : '';
                    }

                    value = value.indexOf("&nbsp;") > -1 ? value.replace(/(.*)&nbsp;/, "$1" + caret) : caret + value;

                    value = row.type=='file' ? "<span class='text-muted'>" + value + "</span>" : value;
                    return '<a href="javascript:;" data-id="' + row.id + '" data-pid="' + row.pid + '" class="'
                        + (row.type=='dir' ? 'text-primary' : 'disabled') + ' btn-node-sub">' + value + '</a>';
                }
            }
        },
        initListen:function (){
             $('#content').after('<div id="diy_content" class="wfb50" style="display: none;"><iframe id="diy_iframe" src=""></iframe></div>');
             $(document).on("change", "#c-type", function(e){
                //�����Ļص��¼�
                var value =$(this).val();
                 //$('.attachfiles').hide();
                 $('.url').hide();
                 $('.page_content').show();
                 $('.identify').show();
                 $('#template').show();
                if (value=='file') {
                    //$('.attachfiles').show();
                } else if (value=='url') {
                     $('.url').show();
                     $('.page_content').hide();
                     $('.identify').hide();
                     $('#template').hide();
                     $('#diy_content').hide();
                     $('#content').parent().removeClass('flex');
                }
            });

            $(document).on("change", "#c-access_type", function(e){
                //�����Ļص��¼�
                var value =$(this).val();
                 $('.password').hide();
                    $('.user_group_ids').hide();
                if (value==1) {
                    $('.password').show();
                } else if (value==2) {
                    $('.user_group_ids').show();
                }
            });

            $('.btn-random').click(function (e) {
                $(this).parent().parent().find('input').val(Knowbase.getRandomStr(32));
            });


            $('#template').click(function (e) {
                e.preventDefault();
                var form = $("form[role=form]");
                var pos = window.location.pathname.indexOf('.php');
                var admin = window.location.pathname.substr(0,pos+4);
                var iframe_value = $('#diy_iframe').attr('value');
                if (iframe_value==undefined) {
                    $('#diy_content').show();
                    $('#content').addClass('wfb50');
                    $('#content').parent().addClass('flex');
                    $('#diy_iframe').attr('src', admin+'/knowbase/project_page_template/templates?group_by_type=1');
                    $('#diy_iframe').attr('value', 'template');
                } else{
                    $('#diy_content').hide();
                    $('#content').parent().removeClass('flex');
                    $('#diy_iframe').removeAttr('value');
                }
                // Layer.open({
                //     type: 2,
                //     content: admin+'/knowbase/project_page_template/templates?group_by_type=1',
                //     zIndex: 99,
                //     area: ['100%','100%'],
                //     title: __('btn_look_template'),
                //     resize: false
                // });
            });
            var scrollHeight = $(document).height();
            // Jquery �������ڹ���
            $(window).scroll(function (e) {
                // ��ȡ��ǰ�����߶�
                var scrollTop = $(this).scrollTop();
                //Jquey �ж� id=diy_content Ԫ���Ƿ�ɼ�
                // if ($('#diy_content').is(':visible')) {
                //     if (scrollTop>=scrollHeight) {
                //         return;
                //     }
                //     // �жϹ������Ƿ񵽵ײ�
                //     if (scrollTop>0) {
                //         $('#diy_iframe').css('top',scrollTop+'px');
                //     } else {
                //         $('#diy_iframe').css('top',0);
                //     }
                // } else {
                //     $('#diy_iframe').css('top',0);
                // }
            });
            $('body').on('click','.page_history.vditor-toolbar__item',function (e){
                if ($('.control-sidebar').hasClass('control-sidebar-open')){
                    $('.control-sidebar').removeClass('control-sidebar-open');
                } else {
                    $('.control-sidebar').addClass('control-sidebar-open');
                }
                return false;
            });
            $('#content').click(function (e){
                if ($('.control-sidebar').hasClass('control-sidebar-open')){
                    $('.control-sidebar').removeClass('control-sidebar-open');
                    return false;
                }
            });
        }
    };
    window.insertTemplate = function (content,id){
        if (window.vditorlist) {
            for (let i in window.vditorlist) {
                if(id && i==id) {
                    window.vditorlist[i].insertValue(content);
                    break;
                }
            }
        }
    };
    return Controller;
});
